// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// u [author] rhyme_lph
// u [email]  rhymelph@gmail.com
// V [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/format/service_and_product_entity.dart';
import 'package:finance_app/src/entities/ocr_attachment_entity.dart';
import 'package:finance_app/src/entities/quotation_detail_entity.dart';
import 'package:finance_app/src/entities/setting_data_entity.dart';
import 'package:finance_app/src/entities/transaction_entity.dart';
import 'package:finance_app/src/provider/dashboard/contact/business_contact_detail_provider.dart';
import 'package:finance_app/src/provider/dashboard/invoice/new_invoice_provider.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/form_utils.dart';
import 'package:finance_app/src/utils/object_utils.dart';
import 'package:finance_app/src/widgets/button/normal_border_button.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/button/normal_text_button.dart';
import 'package:finance_app/src/widgets/common/tag_widget.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/currency_exchange.dart';
import 'package:finance_app/src/widgets/form/add_form.dart';
import 'package:finance_app/src/widgets/form/attach_file_form.dart';
import 'package:finance_app/src/widgets/form/form_edit_status_inherited_widget.dart';
import 'package:finance_app/src/widgets/form/price_form.dart';
import 'package:finance_app/src/widgets/form/service_and_product_form_item.dart';
import 'package:finance_app/src/widgets/form/status_line_form.dart';
import 'package:finance_app/src/widgets/form/value_select_form.dart';
import 'package:finance_app/src/widgets/input/form_input_field.dart';
import 'package:finance_app/src/widgets/form/text_area_input_form.dart';
import 'package:finance_app/src/widgets/list_item/chart_account_open_balance_item.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/quotation/new_quotation_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "newQuotationPage")
class NewQuotationPage extends StatefulWidget {
  final TransactionEntity data;
  final bool isSelectMode;

  const NewQuotationPage({Key key, this.data, this.isSelectMode}) : super(key: key);

  @override
  _NewQuotationPageState createState() => _NewQuotationPageState();
}

class _NewQuotationPageState extends State<NewQuotationPage> with PagePresenter<NewQuotationPage, NewQuotationProvider> {
  String get title => provider.data == null && pageStatus != PageStatus.loading
      ? S.current.new_quotation
      : provider.isEdit == true
          ? S.current.edit_quotation
          : S.current.quotation;

  Widget get rightButton => listBuilder<bool>(
        selector: (_, __) => __.isEdit == false && __.data != null,
        builder: (BuildContext context, bool value, Widget child) => value ? _buildPopButton() : _buildSaveBtn(),
      );

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
          titleWidget: listBuilder<Tuple2<QuotationDetailEntity, bool>>(
            selector: (_, __) => Tuple2(__.data, __.isEdit),
            builder: (BuildContext context, Tuple2<QuotationDetailEntity, bool> value, Widget child) => Text(title),
          ),
          actions: [
            rightButton,
          ]);

  @override
  void initState() {
    provider.isSelectMode = widget.isSelectMode;
    provider.currency = Config.defaultCurrency;
    provider.normalCurrency = Config.defaultCurrency;
    final pro = Providers.get<BusinessContactDetailProvider>(RouterGenProviders.businessContactDetailPage, null);
    if (pro != null) {
      provider.client = pro.contact;
    }
    final invoiceProvider = Providers.get<NewInvoiceProvider>(RouterGenProviders.newInvoicePage, null);
    if (invoiceProvider != null) {
      provider.client = invoiceProvider.client;
    }
    provider.init(widget.data?.transactionableId);
    super.initState();
  }

  Widget _buildPopButton() => listBuilder<bool>(
      selector: (_, __) => __.isEdit && __.data.status != 'closed',
      builder: (BuildContext context, bool value, Widget child) => value == true ? Container() : child,
      child: listBuilder<List<String>>(
        selector: (_, __) => List.from(__.menuList),
        builder: (BuildContext context, List<String> value, Widget child) => NormalMorePopupButton(
          onSelect: provider.onSelectMenu,
          menuList: value,
        ),
      ));

  Widget _buildSaveBtn() {
    return listBuilder<bool>(
      selector: (_, __) => pageStatus != PageStatus.loading,
      builder: (BuildContext context, bool value, Widget child) => value == true
          ? NormalSaveTextButton(
              onTap: provider.onSave,
            )
          : Container(),
    );
  }

  @override
  Widget wrapperBody(Widget child) {
    return listBuilder<bool>(
      selector: (_, __) => __.isEdit == true || provider.id == null,
      builder: (BuildContext context, bool value, Widget child) => FormEditStatusInheritedWidget(
        isEdit: value,
        child: child,
      ),
      child: child,
    );
  }

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: ListView(
          children: [
            listBuilder<String>(
              selector: (_, __) => __.data?.isOverdue == 1 && __.data?.status == 'open' ? 'Overdue' : __.data?.status,
              builder: (BuildContext context, String value, Widget child) => StatusLineForm(
                status: value,
                model: ReimburseModel.quotation,
              ),
            ),
            listBuilder<String>(
              selector: (_, __) => __.client?.name,
              builder: (BuildContext context, String value, Widget child) => ValueSelectForm(
                title: S.current.client_name,
                onTap: provider.onChangeClientName,
                value: value,
              ),
            ),
            Stack(
              children: [
                listBuilder<bool>(
                  selector: (_, __) => __.numberHasError,
                  builder: (BuildContext context, bool value, Widget child) => FromInputField(
                    controller: provider.quotationNumberController,
                    focusNode: provider.quotationNumberFocusNode,
                    tip: S.current.quotation_number,
                    hasError: value,
                  ),
                ),
                Align(
                  alignment: Alignment.centerRight,
                  child: listBuilder<bool>(
                    selector: (_, __) => __.isDelivered,
                    builder: (BuildContext context, bool value, Widget child) => value == true
                        ? Container(
                            margin: EdgeInsets.only(right: getDp(35), top: getDp(20)),
                            child: BlueTagWidget(
                              content: S.current.delivered,
                            ),
                          )
                        : Container(),
                  ),
                )
              ],
            ),
            listBuilder<DateTime>(
              selector: (_, __) => __.date,
              builder: (BuildContext context, DateTime value, Widget child) => ValueSelectForm(
                title: S.current.issue_date,
                value: ObjectUtils.isNullDefaultFormat<DateTime>(value, null, (data) => DateTimeUtils.formatGlobalDateTime(data)),
                onTap: provider.onChangeIssueDate,
              ),
            ),
            listBuilder<DateTime>(
              selector: (_, __) => __.validUntil,
              builder: (BuildContext context, DateTime value, Widget child) => ValueSelectForm(
                title: S.current.valid_until,
                value: ObjectUtils.isNullDefaultFormat<DateTime>(value, null, (data) => DateTimeUtils.formatGlobalDateTime(data)),
                onTap: provider.onChangeValidUntil,
              ),
            ),
            listBuilder<String>(
              selector: (_, __) => __.currency?.name,
              builder: (BuildContext context, String value, Widget child) => ValueSelectForm(
                title: S.current.currency,
                value: value,
                onTap: provider.onChangeCurrency,
                border: null,
              ),
            ),
            Divider(),
            dataBuilder(
              (NewQuotationProvider provider) => CurrencyExchange(
                domesticCurrencyAmount: '1.00',
                foreignCurrencyAmount: provider.changeAmount,
                foreignCurrency: provider.currency.key,
                domesticCurrency: provider.normalCurrency.key,
                amountChange: (str) => provider.amountChange(str),
              ),
            ),
            AppSpaces.grayH6,
            listBuilder<int>(
              selector: (_, __) => List<ServiceAndProductEntity>.from(__.serviceAndProductList).length,
              builder: (BuildContext context, int value, Widget child) => value != 0
                  ? Column(
                      children: [
                        // AppSpaces.grayH6,
                        ...List.generate(
                            value,
                            (index) => listBuilder<Tuple4<ServiceAndProductEntity, int, num, SettingDataTax>>(
                                  selector: (_, __) => Tuple4(__.serviceAndProductList[index], __.serviceAndProductList[index].number,
                                      __.serviceAndProductList[index].discountedAmount, __.serviceAndProductList[index].tax),
                                  builder: (BuildContext context, Tuple4<ServiceAndProductEntity, int, num, SettingDataTax> value, Widget child) =>
                                      ServiceAndProductFormItem(
                                    onTap: () => provider.onSelectItem(value.item1),
                                    productEntity: value.item1,
                                    hasError: false,
                                    showHeader: index == 0,
                                    isLastElement: provider.serviceAndProductList.length == index + 1 && provider.id != null && provider.isEdit == false,
                                  ),
                                ))
                      ],
                    )
                  : ValueSelectForm(
                      title: S.current.item__quantity__amount__tax_rate,
                      onTap: provider.onAddItem,
                    ),
            ),
            AddForm(
              title: S.current.add_item,
              onTap: provider.onAddItem,
            ),
            AppSpaces.grayH6,
            FormStatusWidget(
              builder: (enable) {
                return NormalFormWrapper(
                  bottomPadding: 0.0,
                  child: Column(
                    children: [
                      // _buildSubTotal(),
                      // _buildGst(),
                      _buildDiscount(),
                      _buildTotal(),
                      _buildIncludes(),
                      SizedBox(
                        height: getDp(25),
                      ),
                    ],
                  ),
                );
              },
            ),
            AppSpaces.grayH6,
            TextAreaInputForm(
              title: S.current.additional_notes_optional,
              controller: provider.notesController,
              focusNode: provider.notesFocusNode,
            ),
            NormalFormWrapper(
              child: listBuilder<Tuple2<List<String>, List<OcrAttachmentEntity>>>(
                selector: (_, __) => Tuple2(List.from(__.files), List.from(__.attachments ?? [])),
                builder: (BuildContext context, Tuple2<List<String>, List<OcrAttachmentEntity>> value, Widget child) => AttachFileForm(
                  onAdd: provider.onAddAttachment,
                  files: value.item1,
                  onSelectFile: provider.onSelectFile,
                  attachments: value.item2,
                  onSelectAttachment: provider.onSelectAttachment,
                ),
              ),
            ),
            FormStatusWidget(
              enable: Container(),
              disable: listBuilder<Tuple2<String, int>>(
                  selector: (_, __) => Tuple2<String, int>(__.data?.status, __.data?.deliveryId),
                  builder: (BuildContext context, Tuple2<String, int> value, Widget child) => Column(
                        children: [
                          if (value.item1 == 'accepted' || value.item1 == 'closed') ...[
                            NormalBorderButton(
                              title: S.current.see_invoice,
                              onTap: provider.onSeeInvoice,
                              isFit: true,
                            ),
                            AppSpaces.h30,
                          ],
                          if (value.item1 == 'open') ...[
                            NormalBorderButton(
                              title: S.current.generate_invoice,
                              onTap: provider.onGenerateInvoice,
                              isFit: true,
                            ),
                            AppSpaces.h30,
                          ],
                          if (value.item2 == null && value.item1 == 'open') ...[
                            NormalBorderButton(
                              title: S.current.generate_delivery_service_order,
                              onTap: provider.onGenerateDelivery,
                              isFit: true,
                            ),
                            AppSpaces.h30,
                          ],
                          if (value.item1 == 'open') ...[
                            NormalBorderButton(
                              title: S.current.mark_as_rejected_,
                              onTap: provider.onReject,
                              isFit: true,
                            ),
                          ],
                          SizedBox(height: 52),
                        ],
                      )),
            )
          ],
        ),
      );

  Widget _buildDiscount() {
    return listBuilder<double>(
      selector: (_, __) => __.discount,
      builder: (BuildContext context, double value, Widget child) => value == null
          ? Container()
          : PressedOpacityButton(
              onPressed: provider.onAddDiscount,
              padding: EdgeInsets.only(bottom: getDp(25)),
              child: PriceForm(
                isHighlight: true,
                title: S.current.discount,
                amount: CashUtils.formatCashAmount(-value),
              ),
            ),
    );
  }

  Widget _buildSubTotal() {
    return listBuilder<double>(
      selector: (_, __) => __.subTotal,
      builder: (BuildContext context, double value, Widget child) => Padding(
        padding: EdgeInsets.only(bottom: getDp(25)),
        child: PriceForm(
          title: S.current.subtotal,
          amount: CashUtils.formatCashAmount(value),
        ),
      ),
    );
  }

  Widget _buildGst() {
    return listBuilder<double>(
      selector: (_, __) => __.gst,
      builder: (BuildContext context, double value, Widget child) => value == 0.00
          ? Container()
          : Padding(
              padding: EdgeInsets.only(bottom: getDp(25)),
              child: PriceForm(
                title: S.current.gst,
                amount: CashUtils.formatCashAmount(value),
              ),
            ),
    );
  }

  Widget _buildTotal() {
    return listBuilder<double>(
      selector: (_, __) => __.totalDiscount,
      builder: (BuildContext context, double value, Widget child) => PriceForm(
        title: S.current.total,
        amount: CashUtils.formatCashAmount(value),
      ),
    );
  }

  Widget _buildIncludes() {
    return Align(
      alignment: Alignment.centerRight,
      child: listBuilder<double>(
          builder: (BuildContext context, double value, Widget child) => Config.currentCompany.enableGst == 0
              ? Container()
              : Container(
                  padding: EdgeInsets.only(top: 2),
                  child: Text(
                    '${S.current.includes_gst} ${CashUtils.formatCashAmount(value)}',
                    style: TextStyle(
                      color: aceDarkGrayColor,
                      fontSize: getSp(14),
                      fontWeight: FontWeight.w400,
                      height: 1,
                    ),
                  ),
                ),
          selector: (_, __) => __.includesGST + __.gst),
    );
  }
}
